package com.sugon.controller.tool;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.AutoLog;
import com.sugon.annotation.NonBusinessParamValid;
import com.sugon.entity.ToolsCheckPlanEntity;
import com.sugon.modules.base.model.vo.BaseApproveParamVO;
import com.sugon.modules.base.model.vo.ProcessProgressConst;
import com.sugon.modules.tools.service.IToolsCheckPlanManager;
import com.sugon.service.SysConfigService;
import com.sugon.service.ToolsCheckPlanService;
import com.sugon.utils.PageUtils;
import com.sugon.utils.ProcessInfoEnum;
import com.sugon.utils.Query;
import com.sugon.utils.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;

/**
 * 工装周期性检测计划，以产线为单位Controller
 *
 * @author sugon
 * @date 2021-09-23 16:26:41
 */
@Controller
@RequestMapping("toolscheckplan")
public class ToolsCheckPlanController {

    @Resource
    private ToolsCheckPlanService toolsCheckPlanService;
    @Resource
    private IToolsCheckPlanManager toolsCheckPlanManager;
    @Resource
    private SysConfigService configService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("toolscheckplan:list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<ToolsCheckPlanEntity> toolsCheckPlanList = toolsCheckPlanService.queryList(query);
        int total = toolsCheckPlanService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(toolsCheckPlanList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("toolscheckplan:info")
    @ResponseBody
    public R info(@PathVariable("id") String id) {
        ToolsCheckPlanEntity toolsCheckPlan = toolsCheckPlanService.queryObject(id);

        return R.ok().put("toolsCheckPlan", toolsCheckPlan);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("toolscheckplan:save")
    @ResponseBody
    public R save(@RequestBody ToolsCheckPlanEntity toolsCheckPlan) {
        // 非业务校验
        if (StrUtil.isEmpty(toolsCheckPlan.getDevLineId()) || toolsCheckPlan.getStartDate() == null || toolsCheckPlan.getEndDate() == null) {
            return R.error("产线ID、开始时间和结束时间必填！");
        }

        // 处理下校验计划起止时间
        toolsCheckPlan.setStartDate(DateUtil.beginOfDay(toolsCheckPlan.getStartDate()));
        toolsCheckPlan.setEndDate(DateUtil.endOfDay(toolsCheckPlan.getEndDate()));

        // 同一个产线的工装检测计划不允许存在时间上的重复
        boolean isExists = toolsCheckPlanService.checkExists(toolsCheckPlan.getDevLineId(), toolsCheckPlan.getStartDate(), toolsCheckPlan.getEndDate());
        if (isExists) {
            return R.error("同一产线的工装检测计划不允许存在时间上的交叉！");
        }
        return toolsCheckPlanManager.newlyAdd(toolsCheckPlan) ? R.ok() : R.error("添加失败，请稍后重试！");
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("toolscheckplan:update")
    @ResponseBody
    public R update(@RequestBody ToolsCheckPlanEntity toolsCheckPlan) {
        toolsCheckPlanService.update(toolsCheckPlan);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("toolscheckplan:delete")
    @ResponseBody
    public R delete(@RequestBody String[] ids) {
        toolsCheckPlanService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<ToolsCheckPlanEntity> list = toolsCheckPlanService.queryList(params);

        return R.ok().put("list", list);
    }

    /**
     * 提交工装周期性检测计划审核
     *
     * @param id
     * @return
     */
    @RequestMapping("/submitApprove/{id}")
    @ResponseBody
    public R submitApprove(@PathVariable("id") String id) {
        // 校验维护计划是否存在
        ToolsCheckPlanEntity checkPlan = toolsCheckPlanService.queryObject(id);
        if (checkPlan == null) {
            return R.error("工装周期性校验计划不存在，请确认！");
        }
        // 只有新建和审核遭拒的计划才可以提交
        Integer planStatus = checkPlan.getStatus();
        if (ProcessProgressConst.DEPT_APPROVING.equals(planStatus)) {
            return R.error("校验计划审核中，请耐心等待！");
        }
        if (ProcessProgressConst.PASSED.equals(planStatus)) {
            return R.error("校验计划已通过审核，请误重复提交！");
        }
        // 提交审核
        return toolsCheckPlanManager.commitApprove(checkPlan) ? R.ok() : R.error();
    }

    @RequestMapping("/apply")
    @ResponseBody
    @NonBusinessParamValid
    public R apply(@Validated @RequestBody BaseApproveParamVO approveParam, BindingResult bindingResult) {
        approveParam.setProcessItem(ProcessInfoEnum.TLS_GZZQJCGL);
        return toolsCheckPlanManager.workshopApprove(approveParam) ? R.ok() : R.error();
    }

    @RequestMapping("/export")
    @ResponseBody
    public void export(@RequestParam String id, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        ToolsCheckPlanEntity toolsCheckPlan = toolsCheckPlanService.queryObject(id);
        Assert.notNull(toolsCheckPlan);
        // 构建模板导出参数
        TemplateExportParams templateExportParams = new TemplateExportParams(configService.getPoiTemplatePath() + "toolsCheckPlanExportTemplate.xlsx");
        modelMap.put(TemplateExcelConstants.FILE_NAME, toolsCheckPlan.getPlanName() + "_" + com.sugon.modules.utils.DateUtil.today());
        modelMap.put(TemplateExcelConstants.PARAMS, templateExportParams);
        modelMap.put(TemplateExcelConstants.MAP_DATA, toolsCheckPlanService.export(id));
        PoiBaseView.render(modelMap, request, response, TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);
    }

}
